package com.lvyp.server.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lvyp.server.pojo.Menu;
import com.lvyp.server.pojo.MenuRole;
import com.lvyp.server.pojo.RespBean;
import com.lvyp.server.pojo.Role;
import com.lvyp.server.service.IMenuRoleService;
import com.lvyp.server.service.IMenuService;
import com.lvyp.server.service.IRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 权限组：分为角色和菜单
 * 1.角色的操作
 * 2.查询角色对应的菜单
 */
@RestController
@RequestMapping("/system/basic/permiss")
public class PermissController {
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IMenuService menuService;
    @Autowired
    private IMenuRoleService menuRoleService;

    /*----------------权限组：角色操作------------------*/

    @ApiOperation(value = "获取所有角色")
    @GetMapping("/")
    public List<Role> getAllRole() {
        return roleService.list();
    }

    @ApiOperation(value = "添加角色")
    @PostMapping("/role")
    public RespBean addRole(@RequestBody Role role) {
        // 因为使用的是security需要角色有前缀ROLE_
        // 判断前端传过来的是否有ROLE_，如果没有就自己加
        if (!role.getName().startsWith("ROLE_")) {
            role.setName("ROLE_"+role.getName());
        }
        if (roleService.save(role)) {
            return RespBean.success("添加成功");
        }
        return RespBean.error("添加失败");
    }

    @ApiOperation(value = "根据id删除一个角色")
    @DeleteMapping("/role/{rid}")
    public RespBean deleteRoleById(@PathVariable("rid") Integer rid) {
        if (roleService.removeById(rid)) {
            return RespBean.success("删除成功");
        }
        return RespBean.error("删除失败");
    }

    /*----------------权限组：菜单操作------------------*/

    @ApiOperation(value = "查询所有菜单")
    @GetMapping("/menus")
    public List<Menu> getAllMenus() {
        return menuService.getAllMenus();
    }

    @ApiOperation(value = "根据角色id查询菜单id")
    @GetMapping("/mid/{rid}")
    public List<Integer> getMidByRid(@PathVariable("rid") Integer rid) {
        // 返回的是对象集合，需要转成integer集合
        List<MenuRole> menuIds = menuRoleService.list(new QueryWrapper<MenuRole>().eq("rid", rid));
        List<Integer> mId = menuIds.stream().map(MenuRole::getMid).collect(Collectors.toList());
        return mId;
    }

    /**
     * 更新角色菜单
     * @param rid 角色id
     * @param mids 菜单id数组
     * @return
     */
    @ApiOperation(value = "更新角色菜单")
    @PutMapping("/")
    public RespBean updateMenuRole(Integer rid,Integer[] mids) {
        return menuRoleService.updateMenuRole(rid,mids);

    }
}
